<?php

namespace app\admin\controller\crm;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Session;
/**
 * 分配客户管理
 *
 * @icon fa fa-circle-o
 */
class Allot extends Backend
{
    
    /**
     * Allot模型对象
     * @var \app\admin\model\Allot
     */
    protected $model = null;
    protected $admin_data = '';
    protected $groupidArray = array();
    public function _initialize()
    {
        parent::_initialize();
        $this->dataLimit = 'auth';
        $this->dataLimitField = 'admin_id';
        //当前是否为关联查询
        $this->relationSearch = true;
        $this->searchFields = 'buser.username,admin.username,admin.nickname,product.product';
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $this->model = new \app\admin\model\Allot;
        $buser = new \app\admin\model\Buser;
        //查询当前admin权限
        $adminData = Session::get("admin");
        $linkAdmin = Db::name('Admin');
        $this->admin_data = $linkAdmin->field('a.*,g.id AS gid,g.name,g.pid')
            ->alias('a')->join('fa_auth_group_access u','a.id = u.uid','LEFT')
            ->join('fa_auth_group g','u.group_id = g.id','LEFT')
            ->where(array('a.id'=>$adminData['id']))->find();
        $linkGroup = Db::name('auth_group');
        //判断当前用户是否是销售部人员
        $user_verification=false;
         $this->user_verification($this->admin_data['pid'],'销售部',$user_verification);
        if($user_verification){
            //销售部人员
            //查询所有下级销售专员
            $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
            $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();//获取用户权限
            foreach ($groupList as $k=>$v){
                $this->groupidArray[] = $v['id'];
            }
            if($adminData['id']==7){
                //销售助理查询圆总的数据
                $this->groupidArray[] = 2;
            }
            $groupData = array();
            if($this->admin_data['id']==6||$this->admin_data['id']==7){
                //查询所有分组
                $groupData = $linkGroup->where(array('pid'=>15,'status'=>'normal'))->select();
            }else if($this->admin_data['pid']==10||$this->admin_data['pid']==11||$this->admin_data['pid']==12){
                //查询当前分组
                $groupData = $linkGroup->where(array('id'=>$this->admin_data['pid'],'status'=>'normal'))->select();
            }
        }else{
            //查询销售部人员
            $this->di_group(13,$this->groupidArray);
            //查询所有分组
            $groupData = $linkGroup->where(array('pid'=>15,'status'=>'normal'))->select();
        }
        $linkAdmin = Db::name('admin');
        $xiaoData = $linkAdmin->field('a.nickname,a.id')->alias('a')
            ->join('fa_auth_group_access c','a.id = c.uid','LEFT')
            ->where(array('c.group_id'=>array('IN',$this->groupidArray)))->select();
        $this->view->assign(array(
            'admin_nickname'=>$adminData['nickname'],
            'admin_group_id'=>$this->admin_data['gid'],
            'admin_data'=>$this->admin_data,
            'genderList'=>$buser->getGenderList(),
            'typeList'=>$this->model->getTypeList(),
            'statusList'=>$buser->getStatusList(),
            'xiaoData'=>$xiaoData,
            'groupData'=>$groupData
        ));
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看网贷分配数据
     */
    public function index()
    {
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $andWhere = array();
            $team = $this->request->param('team');//判断团队查询
            $wf_group_id = $this->request->param('wf_group_id');//判断团队查询
            $wf_admin_id = $this->request->param('wf_admin_id');//判断团队查询
            if($team){
                //查询团队任务
                $this->dataLimit = '';
                $this->dataLimitField = '';
                if($wf_admin_id){
                    //查询当前销售任务
                    $andWhere['allot.admin_id'] = $wf_admin_id;
                }else if($wf_group_id){
                    //查询当前分组下销售任务
                    $groupArray = array();
                    $this->di_group($wf_group_id,$groupArray);
                    if($wf_group_id==12){
                        $groupArray[] = 2;
                    }
                    $linkAdmin = Db::name('auth_group_access');
                    $adminIdArray = $linkAdmin->where(array('group_id'=>array('IN',$groupArray)))->column('uid');
                    $andWhere['allot.admin_id'] = array('IN',$adminIdArray);
                }else{
                    //默认查询权限内的数据
                    $linkAuth = Db::name('Auth_group_access');
                    $admin_id = $linkAuth->where(array('group_id'=>array('IN',$this->groupidArray)))->column('uid');
                    if($admin_id){
                        $andWhere['allot.admin_id'] = array('IN',$admin_id);
                    }
                }
            }else{
                //默认查询自己参与的任务
                if($this->admin_data['gid']==1){
                    //超管
                    $andWhere['allot.admin_id'] = $this->admin_data['id'];
                }else{
                    $this->dataLimit = 'personal';
                    $this->dataLimitField = 'admin_id';
                }
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['buser','admin','product'])
                    ->where($where)
                    ->where($andWhere)
                    ->where(array('allot.userlist'=>1))
                    ->order($sort, $order)
                    ->count();
            $list = $this->model
                    ->with(['buser','admin','product'])
                    ->where($where)
                    ->where($andWhere)
                    ->where(array('allot.userlist'=>1))
                   /* ->whereTime('expire_date','between', ['1970-10-1', date('Y-m-d H:i:s')])*/
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            foreach ($list as $row) {
                $row->visible(['id','expire_date','allot_date','followuptime','status','beilist','typelist','qilist','highlist']);
                $row->visible(['buser']);
				$row->getRelation('buser')->visible(['username','pinname','contacts','qq','wechat','mobile','email','status','gender','birthday','hobby','station']);
				$row->visible(['admin']);
				$row->getRelation('admin')->visible(['nickname']);
				$row->visible(['product']);
				$row->getRelation('product')->visible(['product']);
            }
            $list = collection($list)->toArray();
            $time = time();
            foreach ($list as $k=>$v){
                //判断是否显示分配按钮
                if($v['expire_date']!='0000-00-00 00:00:00'){
                        /*if($time>=$daoTime&&$v['status']!=6){
                            //分配时间到期&&还没签约的可以从新分配客服
                            if($this->admin_data['gid']==1||$this->admin_data['gid']==2){
                                $list[$k]['fen'] = 'show';
                            }else{
                                $list[$k]['fen'] = 'hide';
                            }
                        }else{
                            $list[$k]['fen'] = 'hide';
                        }*/
                        //计算过期时间
                        $qiMiao = strtotime($v['expire_date']);
                        $yuMiao = $qiMiao-$time;
                        if($yuMiao>=86400){
                            //计算天
                            $qi = ceil($yuMiao/86400).'天';
                        }else if($yuMiao<86400&&$yuMiao>=3600){
                            //计算小时
                            $qi = ceil($yuMiao/3600).'小时';
                        }else if($yuMiao<3600&&$yuMiao>=60){
                            //计算分
                            $qi = ceil($yuMiao/60).'分钟';
                        }else if($yuMiao<60&&$yuMiao>=0){
                            $qi = $yuMiao.'秒';
                        }else
                        {
                            $qi = '已过期';
                        }
                        $list[$k]['qi'] = $qi;
                }else{
                    //已经分配过
                    $list[$k]['fen'] = 'hide';
                    $list[$k]['qi'] = '没有期限';
                }
            }
            //查询已经到期的平台
            $qiCount = $this->model->alias('allot')
                        ->join('fa_buser buser','buser.id = allot.buser_id','LEFT')
                        ->join('fa_admin admin','admin.id = allot.admin_id','LEFT')
                        ->join('fa_product product','product.id = allot.product_id','LEFT')
                        ->where(array('allot.qilist'=>2,'allot.userlist'=>1))
                        ->where($where)
                        ->where($andWhere)
                        ->count();
            $result = array("total" => $total, "rows" => $list,'qiCount'=>$qiCount);
            return json($result);
        }
        //查询状态值
        $statusData = $this->model->getStatusList();
        $this->view->assign('statusData',$statusData);
        $this->view->assign('admin_group_id',$this->admin_data['gid']);
        return $this->view->fetch();
    }

    /**
     * 查询可分配的网贷用户
     */
    public function distribution(){
        if($this->request->isAjax()){
            $param = $this->request->param();
            $param['wf_group_id'] = isset($param['wf_group_id'])?$param['wf_group_id']:'';
            $param['wf_admin_id'] = isset($param['wf_admin_id'])?$param['wf_admin_id']:'';
            $adminWhere = array();
            if($param['wf_admin_id']){
                $adminWhere['admin.id'] = $param['wf_admin_id'];
            }else if($param['wf_admin_id']){
                $groupArray = array();
                $this->di_group($param['wf_admin_id'],$groupArray);
                if($param['wf_admin_id']==12){
                    $groupArray[] = 2;
                }
                $linkAdmin = Db::name('auth_group_access');
                $adminIdArray = $linkAdmin->where(array('group_id'=>array('IN',$groupArray)))->column('uid');
                $adminWhere['admin.id'] = array('IN',$adminIdArray);
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['buser','admin','product'])
                ->where($where)
                ->where($adminWhere)
                ->where(array('allot.status'=>array('NOT IN','6'),'allot.userlist'=>'1'))
                ->whereTime('expire_date','between', ['1970-10-1', date('Y-m-d H:i:s')])
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with(['buser','admin','product'])
                ->where($where)
                ->where($adminWhere)
                ->where(array('allot.status'=>array('NOT IN','6'),'allot.userlist'=>'1'))
                ->whereTime('expire_date','between', ['1970-10-1', date('Y-m-d H:i:s')])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $row) {
                $row->visible(['id','expire_date','allot_date','followuptime','status','beilist','typelist','qilist']);
                $row->visible(['buser']);
                $row->getRelation('buser')->visible(['username','contacts','qq','wechat','mobile','email','status','gender','birthday','hobby','station']);
                $row->visible(['admin']);
                $row->getRelation('admin')->visible(['nickname']);
                $row->visible(['product']);
                $row->getRelation('product')->visible(['product']);
            }
            $list = collection($list)->toArray();
            $time = time();
            foreach ($list as $k=>$v){
                //判断是否显示分配按钮
                $daoTime = strtotime($v['expire_date']);
                if($daoTime){
                    if($time>=$daoTime&&$v['status']!=6){
                        //分配时间到期&&还没签约的可以从新分配客服
                        if($this->admin_data['gid']==1||$this->admin_data['gid']==2){
                            $list[$k]['fen'] = 'show';
                        }else{
                            $list[$k]['fen'] = 'hide';
                        }
                    }else{
                        $list[$k]['fen'] = 'hide';
                    }
                }else{
                    $list[$k]['fen'] = 'hide';
                }
                $list[$k]['qi'] = '已到期';
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 到期分配客户
     * 适用于所有类型的客户
     */
    public function expired_allot($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $groupList = collection(AuthGroup::where('id', 'in', $this->auth->getChildrenGroupIds(true))->select())->toArray();
        Tree::instance()->init($groupList);
        $result = []; //有权限的分组
        if ($this->auth->isSuperAdmin())
        {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        }
        else
        {
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n)
            {
                $result = array_merge($result, Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['pid'])));
            }
        }
        $alloted=Db::name('allot')->where(array('buser_id'=>$row->toArray()['buser_id'],'product_id'=>$row->toArray()['product_id'],'userlist'=>''.$row->toArray()['userlist'].''))->column('admin_id');
        foreach ($result as $v)
        {
            $admin = Db::name('admin a')->join('auth_group_access aga','a.id=aga.uid')
                ->where('aga.group_id',$v['id'])->field('a.id admin_id,nickname')->select();
            if($admin)
            {
                foreach ($admin as $val)
                {
                    if(!in_array($val['admin_id'],$alloted)) //没有分配过的
                    {
                        $v['admins'][]=$val;
                    }
                }
            }
            $admins[] = $v;
        }
        $this->view->assign('admins',$admins);
        if ($this->request->isPost()) {
            $params = $this->request->post();
            //检查当前admin身份
            $linkAdmin = Db::name('Admin');
            $adminUser = $linkAdmin->field('g.pid')
                ->alias('a')->join('fa_auth_group_access u','a.id = u.uid','LEFT')
                ->join('fa_auth_group g','u.group_id = g.id','LEFT')
                ->where(array('a.id'=>$params['admin_id']))->find();
            $user_verification=false;
            $this->user_verification($adminUser['pid'],'销售部',$user_verification);
            if(!$user_verification){
                $this->error('只能分配给销售部的小伙伴');
            }
            //检查当前数据是否已经分配过了
            $allotData = $this->model->where(array('id'=>$ids))->find();
            if(!$allotData){
                $this->error(__('当前分配数据不存在'));
            }if($allotData['expire_date']=='0000-00-00 00:00:00'){
                $this->error(__('当前数据已经分配过了'));
            }
            //检查当前销售是否分配过当前客户
            $buserData = $this->model->where(array('buser_id'=>$row['buser_id'],'admin_id'=>$params['admin_id'],'userlist'=>''.$allotData['userlist'].''))->find();
            if ($params) {
                   Db::startTrans();
                try {
                    $day=Db::name('allot_expire')->where('id',2)->value('expire');
                    $add = Db::name('allot')->insertGetId([
                        'buser_id'=>$row['buser_id'],
                        'admin_id'=>$params['admin_id'],
                        'product_id'=>$row['product_id'],
                        'expire_date'=>date('Y-m-d H:i:s',strtotime('+'.$day.' days')),
                        'status'=>''.$allotData['status'].'',
                        'userlist'=>''.$allotData['userlist'].'',
                        'allot_date'=>date('Y-m-d H:i:s'),
                    ]);
                   $save =  Db::name('allot')->where('id',$row['id'])->update(['expire_date'=>'0000-00-00 00:00:00']);
                    if(!$buserData){
                        //当前客服没有分配当前客户
                        if($allotData['userlist']==1){
                            //网贷客户
                            Db::name('Buser')->where(array('id'=>$row['buser_id']))->setInc('admin_ids',1);
                        }else{
                            //金融类客户
                            Db::name('Bkuser')->where(array('id'=>$row['buser_id']))->setInc('admin_ids',1);
                        }

                    }
                    if($add&&$save){
                        //分配成功
                        Db::commit();
                        $this->success();
                    }else{
                        Db::rollback();
                        $this->error('操作失败');
                    }
                } catch (\think\exception\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 推荐产品
     * 适用于所有类型的客户
     * $ids :客户ID
     */
    public function push_products($ids=''){
        if(empty($ids)){
            $this->error('非法操作');
        }
        $linkBuser = Db::name('Buser');
        $buserData = $linkBuser->where(array('id'=>$ids))->find();
        if(!$buserData){
            $this->error('不存在当前客户信息');
        }
        if($this->request->isPost()){
            //POST提交
            $param = $this->request->param();
            if(empty($param['product_id'])){
                $this->error(__('请选择产品'));
            }else if(empty($param['admin_id'])){
                $this->error('请选择跟踪销售专员');
            }
            $linkAdmin = Db::name('Admin');
            $adminUser = $linkAdmin->field('g.pid')
                ->alias('a')->join('fa_auth_group_access u','a.id = u.uid','LEFT')
                ->join('fa_auth_group g','u.group_id = g.id','LEFT')
                ->where(array('a.id'=>$param['admin_id']))->find();
            $user_verification=false;//判断身份
            $this->user_verification($adminUser['pid'],'销售部',$user_verification);
            if(!$user_verification){
                $this->error('只能分配给销售部的小伙伴');
            }
            //检查当前产品是否分配给客户
            $product_id = explode(',',$param['product_id']);
            if($product_id){
                //查询期限表
                Db::startTrans();
                $linkQi = Db::name('allot_expire');
                $linkPlan = Db::name('product');
                $qiData = $linkQi->where(array('id'=>1))->find();
                $add = false;
                foreach ($product_id as $k=>$v){
                    $planData = $linkPlan->where(array('id'=>$v))->find();
                    if($planData){
                        $allotCount = $this->model->where(array('product_id'=>$v,'buser_id'=>$ids,'userlist'=>'1'))->count();
                        if(!$allotCount){
                            //没有推荐过当前产品
                            //写入数据
                            $field = array(
                                'buser_id'=>$ids,
                                'admin_id'=>$param['admin_id'],
                                'product_id'=>$v,
                                'userlist'=>'1',
                                'expire_date'=>date('Y-m-d H:i:s',strtotime('+'.$qiData['expire'].' day')),
                                'allot_date'=>date('Y-m-d H:i:s',time()),
                            );
                           $allotAdd =  Db::name('allot')->insertGetId($field);
                           if($allotAdd){
                               //推广成功
                               $add = true;
                           }else{
                               Db::rollback();
                               $this->error('推广失败');
                           }
                        }
                    }else{
                        Db::rollback();
                        $this->error('请先录入推荐产品');
                    }
                }
                if($add){
                    Db::commit();
                    $this->success(__('推荐成功'));
                }else{
                    Db::rollback();
                    $this->error('推广失败');
                }
            }else{
                $this->error(__('推荐失败请刷新重试'));
            }

        }else{
            //GET
            $groupList = collection(AuthGroup::where('id', 'in', $this->auth->getChildrenGroupIds(true))->select())->toArray();
            Tree::instance()->init($groupList);
            $result = []; //有权限的分组
            if ($this->auth->isSuperAdmin())
            {
                $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            }
            else
            {
                $groups = $this->auth->getGroups();
                foreach ($groups as $m => $n)
                {
                    $result = array_merge($result, Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['pid'])));
                }
            }
            foreach ($result as $v)
            {
                $admin = Db::name('admin a')->join('auth_group_access aga','a.id=aga.uid')
                    ->where('aga.group_id',$v['id'])->field('a.id admin_id,nickname')->select();
                if($admin)
                {
                    foreach ($admin as $val)
                    {
                        $v['admins'][]=$val;
                    }
                }
                $admins[] = $v;
            }
            $this->view->assign(array(
                'admins'=>$admins,
                'ids'=>$ids
            ));
            return  $this->view->fetch();
        }
    }

    /**
     * 推广产品
     */
    public function product(){
        $this->dataLimit = '';
        $this->dataLimitField = '';
        $this->searchFields = 'buser.username';
        if($this->request->isAjax()){
            //查询已经签约的客户
            $linkAllot = Db::name('Allot');
            $linkproduct = Db::name('product');
            $allotData = $linkAllot->alias('a')->field('buser_id,product_id')
                        ->join('fa_product p','a.product_id = p.id','LEFT')
                        ->where(array('p.type'=>1,'a.userlist'=>'1'))->order('buser_id')
                        ->group('buser_id,product_id')->select();
            $productCount = $linkproduct->where(array('type'=>1))->count();
            $buser_id = array();
            $buserArray = array('',0);
            foreach ($allotData as $k=>$v){
                if($buserArray[0]!=$v['buser_id']&&$k>0){
                    if($buserArray[1]<$productCount){
                        //可以推荐的用户
                        $buser_id[] = $buserArray[0];
                    }
                    $buserArray[1] = 0;
                }
                $buserArray[0] = $v['buser_id'];
                $buserArray[1]+=1;
            }
            if($buserArray[0]){
                if($buserArray[1]<$productCount){
                    $buser_id[] = $buserArray[0];
                }
            }
            $linkBuser = new \app\admin\model\Buser();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $linkBuser->alias('buser')
                    ->where(array('buser.id'=>array('IN',$buser_id)))
                    ->where($where)
                    ->count();
            $list = $linkBuser->alias('buser')
                    ->where(array('buser.id'=>array('IN',$buser_id)))
                    ->where($where)
                    ->limit($offset, $limit)
                    ->select();
            foreach ($list as $row) {
                $row->visible(['id','username','contacts','qq','wechat','mobile','email','status','gender','birthday','hobby','station']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     *
     * 金融类客户分配
     *
     */
    public function finance_user(){
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $andWhere = array();
            $team = $this->request->param('team');//判断团队查询
            $wf_group_id = $this->request->param('wf_group_id');//判断团队查询
            $wf_admin_id = $this->request->param('wf_admin_id');//判断团队查询
            if($team){
                //查询团队任务
                $this->dataLimit = '';
                $this->dataLimitField = '';
                if($wf_admin_id){
                    //查询当前销售任务
                    $andWhere['allot.admin_id'] = $wf_admin_id;
                }else if($wf_group_id){
                    //查询当前分组下销售任务
                    $groupArray = array();
                    $this->di_group($wf_group_id,$groupArray);
                    if($wf_group_id==12){
                        $groupArray[] = 2;
                    }
                    $linkAdmin = Db::name('auth_group_access');
                    $adminIdArray = $linkAdmin->where(array('group_id'=>array('IN',$groupArray)))->column('uid');
                    $andWhere['allot.admin_id'] = array('IN',$adminIdArray);
                }else{
                    //默认查询权限内的数据
                    $linkAuth = Db::name('Auth_group_access');
                    $admin_id = $linkAuth->where(array('group_id'=>array('IN',$this->groupidArray)))->column('uid');
                    if($admin_id){
                        $andWhere['allot.admin_id'] = array('IN',$admin_id);
                    }
                }
            }else{
                //默认查询自己参与的任务
                if($this->admin_data['gid']==1){
                    //超管
                    $andWhere['allot.admin_id'] = $this->admin_data['id'];
                }else{
                    $this->dataLimit = 'personal';
                    $this->dataLimitField = 'admin_id';
                }
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['bkuser','admin','product'])
                ->where($where)
                ->where($andWhere)
                ->where(array('allot.userlist'=>'2'))
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with(['bkuser','admin','product'])
                ->where($where)
                ->where($andWhere)
                ->where(array('allot.userlist'=>'2'))
                /* ->whereTime('expire_date','between', ['1970-10-1', date('Y-m-d H:i:s')])*/
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->visible(['id','expire_date','allot_date','followuptime','status','beilist','typelist','qilist','highlist']);
                $row->visible(['bkuser']);
                $row->getRelation('bkuser')->visible(['company','username','company_address','company_url','office_tel','qq','wechat','mobile','email','status','gender','birthday','qq_friend','wecaht_friend','station']);
                $row->visible(['admin']);
                $row->getRelation('admin')->visible(['nickname']);
                $row->visible(['product']);
                $row->getRelation('product')->visible(['product']);
            }
            $list = collection($list)->toArray();
            $time = time();
            foreach ($list as $k=>$v){
                //判断是否显示分配按钮
                if($v['expire_date']!='0000-00-00 00:00:00'){
                    $daoTime = strtotime($v['expire_date']);
                    if($time>=$daoTime&&$v['status']!=6){
                        //分配时间到期&&还没签约的可以从新分配客服
                        if($this->admin_data['gid']==1||$this->admin_data['gid']==2){
                            $list[$k]['fen'] = 'show';
                        }else{
                            $list[$k]['fen'] = 'hide';
                        }
                    }else{
                        $list[$k]['fen'] = 'hide';
                    }
                    //计算过期时间
                    $qiMiao = strtotime($v['expire_date']);
                    $yuMiao = $qiMiao-$time;
                    if($yuMiao>=86400){
                        //计算天
                        $qi = ceil($yuMiao/86400).'天';
                    }else if($yuMiao<86400&&$yuMiao>=3600){
                        //计算小时
                        $qi = ceil($yuMiao/3600).'小时';
                    }else if($yuMiao<3600&&$yuMiao>=60){
                        //计算分
                        $qi = ceil($yuMiao/60).'分钟';
                    }else if($yuMiao<60&&$yuMiao>=0){
                        $qi = $yuMiao.'秒';
                    }else
                    {
                        $qi = '已过期';
                    }
                    $list[$k]['qi'] = $qi;
                }else{
                    //已经分配过
                    $list[$k]['fen'] = 'hide';
                    $list[$k]['qi'] = '没有期限';
                }
            }
            //查询已经到期的平台
            $qiCount = $this->model->alias('allot')
                ->join('fa_bkuser bkuser','bkuser.id = allot.buser_id','LEFT')
                ->join('fa_admin admin','admin.id = allot.admin_id','LEFT')
                ->join('fa_product product','product.id = allot.product_id','LEFT')
                ->where(array('allot.qilist'=>2,'allot.userlist'=>'2'))
                ->where($where)
                ->where($andWhere)
                ->count();
            $result = array("total" => $total, "rows" => $list,'qiCount'=>$qiCount);
            return json($result);
        }
        //查询状态值
        $statusData = $this->model->getStatusList();
        $this->view->assign('statusData',$statusData);
        $this->view->assign('admin_group_id',$this->admin_data['gid']);
        return $this->view->fetch();
    }

    /**
     * 待跟进网贷客户查询
     */
    public function followup(){
        if($this->request->isAjax()){
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            //查询截至当前时间可以跟进的用户
            $andWhere = array(
                'admin.id'=>$this->admin_data['id'],
                'allot.userlist'=>1,
                'allot.status'=>array('NOT IN',6)
            );
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['buser','admin','product'])
                ->where($where)
                ->where($andWhere)
                ->whereTime('allot.nexttime','between', ['1970-10-1', date('Y-m-d',time())])
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with(['buser','admin','product'])
                ->where($where)
                ->where($andWhere)
                ->whereTime('allot.nexttime','between', ['1970-10-1', date('Y-m-d',time())])
                /* ->whereTime('expire_date','between', ['1970-10-1', date('Y-m-d H:i:s')])*/
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $row) {
                $row->visible(['id','expire_date','nexttime','allot_date','followuptime','status','beilist','typelist','qilist','highlist']);
                $row->visible(['buser']);
                $row->getRelation('buser')->visible(['username','contacts','qq','wechat','mobile','email','gender','birthday','hobby','station']);
                $row->visible(['admin']);
                $row->getRelation('admin')->visible(['nickname']);
                $row->visible(['product']);
                $row->getRelation('product')->visible(['product']);
            }
            $list = collection($list)->toArray();
            $time = time();
            foreach ($list as $k=>$v){
                //判断是否显示分配按钮
                if($v['expire_date']!='0000-00-00 00:00:00'){
                    /*if($time>=$daoTime&&$v['status']!=6){
                        //分配时间到期&&还没签约的可以从新分配客服
                        if($this->admin_data['gid']==1||$this->admin_data['gid']==2){
                            $list[$k]['fen'] = 'show';
                        }else{
                            $list[$k]['fen'] = 'hide';
                        }
                    }else{
                        $list[$k]['fen'] = 'hide';
                    }*/
                    //计算过期时间
                    $qiMiao = strtotime($v['expire_date']);
                    $yuMiao = $qiMiao-$time;
                    if($yuMiao>=86400){
                        //计算天
                        $qi = ceil($yuMiao/86400).'天';
                    }else if($yuMiao<86400&&$yuMiao>=3600){
                        //计算小时
                        $qi = ceil($yuMiao/3600).'小时';
                    }else if($yuMiao<3600&&$yuMiao>=60){
                        //计算分
                        $qi = ceil($yuMiao/60).'分钟';
                    }else if($yuMiao<60&&$yuMiao>=0){
                        $qi = $yuMiao.'秒';
                    }else
                    {
                        $qi = '已过期';
                    }
                    $list[$k]['qi'] = $qi;
                }else{
                    //已经分配过
                    $list[$k]['fen'] = 'hide';
                    $list[$k]['qi'] = '没有期限';
                }
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }else{
            return $this->view->fetch();
        }
    }
}
